<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model = "html"
        :defaultConfig="editorConfig"
        mode="default"
        @onCreated="handleCreated"
    />
  </div>

</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, shallowRef, onMounted, watch, ref, computed} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const props = defineProps({
  modelValue:{
    type:String,
    default:'<h1>提示</h1><p>请设定:rich属性,用于展示默认的填充值,如果不需要填充值,设置它为空!</p>'
  },
  disabled:{
    type:Boolean
  }
})

const emit = defineEmits(['richChange','update:modelValue'])
const html = ref('')

watch(html,()=>{
  emit('update:modelValue',html)
  emit('richChange')
})

watch(props,()=>{
  if (props.disabled) {
    handleDisabled()
  } else {
    handleReleased()
  }
})

// 模拟 ajax 异步获取内容
onMounted(() => {

})

const toolbarConfig = {}
const editorConfig = { placeholder: '在此處鍵入信息' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  html.value = props.modelValue
}

const handleDisabled = () => {
  const editor = editorRef.value
  if(editor == null) return
  editor.disable()
}

const handleReleased = () => {
  const editor = editorRef.value
  if(editor == null) return
  editor.enable()
}

</script>

<style scoped>

</style>